package com.cyz.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyz.dao.QuartzMapper;
import com.cyz.entity.Trigger;
import com.cyz.service.QuartzService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class QuartzServiceImpl extends ServiceImpl<QuartzMapper, Trigger> implements QuartzService {
    @Autowired
    private QuartzMapper quartzMapper;

    @Autowired
    private Scheduler scheduler;

    @Override
    public void refreshTrigger() {
        //获得所有的任务
        List<Trigger> triggers = quartzMapper.selectList(null);


        if( triggers != null){  //数据库中存在任务
            for (Trigger trigger1 : triggers) {
                //System.out.println(trigger);

                if(trigger1.getStatus() == 1) {  //1表示正常启用

                    //拿出一个任务，启动一个任务
                    try {
                        //1.定义JobDetail，将HelloJob类添加到JobDetail对象中（添加到Job清单）
                        //com.example.job.YRJob
                        JobDetail jobDetail = JobBuilder.newJob((Class<? extends Job>) Class.forName(trigger1.getJobClass()))
                                //任务的名字和组的名字（坑）
                                //任务名字不能相同
                                .withIdentity(trigger1.getJobName(), trigger1.getJobGroup())
                                .build();

                        //2.定义Trigger触发器，使用简单触发器，设置name/group
                        org.quartz.Trigger trigger = TriggerBuilder.newTrigger()
                                .withIdentity(trigger1.getTriggerName(), trigger1.getTriggerGroup())
                                .startNow()
                                .withSchedule(CronScheduleBuilder.cronSchedule(trigger1.getCron()))
                                .build();

                        //3.创建scheduler调度器
                        scheduler.scheduleJob(jobDetail, trigger);
                        //启动调度器
                        scheduler.start();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        }

    }
}
